//
//  AppDelegate.m
//  CoderLLT
//
//  Created by 刘晓萌 on 15/12/9.
//  Copyright © 2015年 刘晓萌. All rights reserved.
//

#import "AppDelegate.h"
#import <AVOSCloud/AVOSCloud.h>

#import "LLT_TabBarController_LXM.h"
#import "LLT_MenuTableViewController_LXH.h"
#import "REFrostedViewController.h"

#import "LLT_PlayerInfoViewController_LXM.h"
#import "LLT_AddPlayerInfoViewController_LXM.h"
#import "LLT_DataViewController_LXM.h"
#import "LLT_NewsViewController_LXH.h"
#import "LLT_VideoViewController_LXH.h"
#import "LLT_LoginViewController_LXM.h"
#import "LLT_PlayerModel.h"


#define getVC(identifier) ( [MainStoryBoard instantiateViewControllerWithIdentifier:identifier])

@interface AppDelegate ()
@property (strong,nonatomic)LLT_PlayerModel *player;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //链接avos
    //如果使用美国站点，请加上这行代码 [AVOSCloud useAVCloudUS];
    [AVOSCloud setApplicationId:@"j9KRKNLSkI0W6qFaHiSamWYz-gzGzoHsz"
                      clientKey:@"B1WranSg14lSfMs7bFGid4EI"];
   
    //是否是自动登陆
    [self autoLogin];
    
    return YES;
}
#pragma mark --- 功能实现

/**
 * 查找是否是有登陆记录 如果有就自动登陆 / 登陆失败或没有就跳转到登陆界面
 */
-(void)autoLogin{
    NSUserDefaults *loginDefault = [NSUserDefaults standardUserDefaults];
    BOOL onlineFlag = [loginDefault boolForKey:@"online"];
    NSDictionary *userDic = [loginDefault dictionaryForKey:@"onlineUser"];
    if (onlineFlag) {
        [AVUser logInWithMobilePhoneNumberInBackground:userDic[@"username"] password:userDic[@"password"] block:^(AVUser *user, NSError *error) {
            if (!error) {
                [self makeMainView];
            }else{
                [self makeRootViewController:getVC(@"loginVC")];
            }
        }];
    }else{
      [self makeRootViewController:getVC(@"loginVC")];
    }
}

/**
 * 设置rootViewController
 */
-(void)makeRootViewController:(UIViewController *)sender{
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = sender;
}

/**
 * 设置显示主界面
 */
-(void)makeMainView{
    __weak typeof(self) weakSelf = self;
    AVQuery *query = [AVQuery queryWithClassName:@"LLT_PlayerInfo"];
    NSDictionary *onlineUser =[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"onlineUser"];
    
    [query whereKey:@"phoneNumber" equalTo:onlineUser[@"username"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            if (objects.count > 0) {
                NSDictionary *dic = objects[0];
                weakSelf.player = [LLT_PlayerModel new];
                weakSelf.player.playerName = dic[@"pname"];
                weakSelf.player.serverName = dic[@"pserverName"];
                [weakSelf makeMainViewByBing:YES];
                
            }else{
                [weakSelf makeMainViewByBing:NO];

            }
        } else {
            [weakSelf makeMainViewByBing:NO];

        }
    }];
}

/**
 * 根据真假判断页面如何调用
 */
-(void)makeMainViewByBing:(BOOL)lock{
    [[NSUserDefaults standardUserDefaults] setBool:lock forKey:@"hasPlayer"];
    LLT_TabBarController_LXM *tabbarController = [self getTabBarWithBrinding:lock];
    LLT_MenuTableViewController_LXH *munuController = [[LLT_MenuTableViewController_LXH alloc]init];
    REFrostedViewController *frostedViewController = [[REFrostedViewController alloc]initWithContentViewController:tabbarController menuViewController:munuController];
    frostedViewController.direction = REFrostedViewControllerDirectionLeft;
    frostedViewController.liveBlurBackgroundStyle = REFrostedViewControllerLiveBackgroundStyleLight;
    frostedViewController.modalTransitionStyle =
    UIModalTransitionStyleFlipHorizontal;
    [self makeRootViewController:frostedViewController];
    
}

/**
 * 设置tabBarController
 */
-(LLT_TabBarController_LXM *)getTabBarWithBrinding:(BOOL)brinding{
    
    LLT_TabBarController_LXM *tabbarController = [LLT_TabBarController_LXM shareTabBar];
    LLT_DataViewController_LXM  *dataVC = getVC(@"dataView_Table");
    LLT_PlayerInfoViewController_LXM  *playVC = getVC(@"playerInfoVC");
    LLT_AddPlayerInfoViewController_LXM  *aPlayVC = getVC(@"addPlayerInfoVC");
    LLT_NewsViewController_LXH  *newsVC = getVC(@"newsVC");
    LLT_VideoViewController_LXH  *lVVC = getVC(@"liveAndVideoVC");
    
    //此处添加判定条件(根据是否绑定游戏角色来判断)
    if (brinding && self.player) {
        NSArray *arr = @[playVC,dataVC,newsVC,lVVC];
        playVC.player = self.player;
        [tabbarController setViewControllers:arr];
    }else{
        NSArray *arr = @[aPlayVC,dataVC,newsVC,lVVC];
        [tabbarController setViewControllers:arr];
    }
    return tabbarController;
}

/**
 *
 */
//关于登陆后的情况 有2种 1是第一次登陆 2是以前登陆过的  第一次登陆的获取个人信息后 照片之类的也都从网上获取 然后保存到本地  2.以前登陆过的直接本地获取照片信息,然后再从网上获取最新的信息,缓存替换到本地上(本地建一个sqlLite来存储管理信息) (第一次登陆的直接设置用户的主页是绑定游戏角色,如果没有绑定游戏角色的就设置页面为游戏人物信息页)



/**
 * 查找是否有过游戏信息的保存
 */





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "lxm.CoderLLT" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoderLLT" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoderLLT.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
